 

package com.zdkj.subway.stm.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zdkj.admin.api.entity.SysDictItem;
import com.zdkj.common.core.constant.CommonConstants;
import com.zdkj.common.core.util.R;
import com.zdkj.common.log.annotation.SysLog;
import com.zdkj.common.security.util.ObjectUtils;
import com.zdkj.subway.stm.constant.StmConstans;
import com.zdkj.subway.stm.constant.StmTableCommon;
import com.zdkj.subway.stm.dto.out.SwStTvmSupplementCurrencyDTO;
import com.zdkj.subway.stm.dvo.SwStmStationDataEntryLogDvo;
import com.zdkj.subway.stm.entity.SwStTvmSupplementCurrency;
import com.zdkj.subway.stm.entity.SwStmStationDataEntryLog;
import com.zdkj.subway.stm.fegin.SystemUserService;
import com.zdkj.subway.stm.mapper.SwStTvmSupplementCurrencyMapper;
import com.zdkj.subway.stm.service.SwStTvmSupplementCurrencyService;
import com.zdkj.subway.stm.service.SwStmStationDataEntryLogService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * TVM补币金额管理
 *
 * @author songtuo
 * @date 2020-07-09 10:33:25
 */
@RestController
@AllArgsConstructor
@RequestMapping("/swsttvmsupplementcurrency" )
@Api(value = "swsttvmsupplementcurrency", tags = "TVM补币金额管理管理")
@Slf4j
public class SwStTvmSupplementCurrencyController {

    private final  SwStTvmSupplementCurrencyService swStTvmSupplementCurrencyService;

    private final SystemUserService systemUserService;
    @Autowired
    private SwStTvmSupplementCurrencyMapper swStTvmSupplementCurrencyMapper;

    private final SwStmStationDataEntryLogService swStmStationDataEntryLogService;

    /**
     * 分页查询
     * @param page 分页对象
     * @param swStTvmSupplementCurrency TVM补币金额管理
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page" )
    public R getSwStTvmSupplementCurrencyPage(Page page, SwStTvmSupplementCurrency swStTvmSupplementCurrency) {
        QueryWrapper<SwStTvmSupplementCurrency> queryWrapper = Wrappers.query(swStTvmSupplementCurrency);
        String dateCondition = swStTvmSupplementCurrency.getSupplementCurrencyTimeDto();
        if (StringUtils.isNotBlank(dateCondition)) {
            queryWrapper.lambda().likeRight(SwStTvmSupplementCurrency::getSupplementCurrencyTime, dateCondition);
        }
        SwStTvmSupplementCurrency supplementCurrencyObj = ObjectUtils.getDefaultObj(SwStTvmSupplementCurrency.class);
        swStTvmSupplementCurrency.setLineCode(supplementCurrencyObj.getLineCode());
        swStTvmSupplementCurrency.setStationCode(supplementCurrencyObj.getStationCode());
        queryWrapper.orderByDesc("SUPPLEMENT_CURRENCY_TIME");
        return R.ok(swStTvmSupplementCurrencyService.page(page, queryWrapper));
    }

    @RequestMapping("/getTvmSupplementCurrency")
    public R getSwStInputPassengerWork(@RequestParam Map<String,String> param){
        List<Map<String, Object>> swStTvmSupplementCurrency = swStTvmSupplementCurrencyMapper.getTvmSupplementCurrencyMap(param);
        return R.ok(swStTvmSupplementCurrency);
    }


    /**
     * 通过id查询TVM补币金额管理
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}" )
    public R getById(@PathVariable("id" ) Integer id) {
        return R.ok(swStTvmSupplementCurrencyService.getById(id));
    }

    /**
     * 新增TVM补币金额管理
     * @param swStTvmSupplementCurrencyDTO TVM补币金额管理
     * @return R
     */
    @ApiOperation(value = "新增TVM补币金额管理", notes = "新增TVM补币金额管理")
    //@SysLog("新增TVM补币金额管理" )
    @PostMapping
    @PreAuthorize("@pms.hasPermission('swsttvmsupplementcurrency_add')" )
    public R save(@RequestBody SwStTvmSupplementCurrencyDTO swStTvmSupplementCurrencyDTO) {
        return R.ok(swStTvmSupplementCurrencyService.saveSwStTvmSupplementCurrency(swStTvmSupplementCurrencyDTO));
    }

    /**
     * 修改TVM补币金额管理
     * @param swStTvmSupplementCurrencyDTO TVM补币金额管理
     * @return R
     */
    @ApiOperation(value = "修改TVM补币金额管理", notes = "修改TVM补币金额管理")
    //@SysLog("修改TVM补币金额管理" )
    @PutMapping
    @PreAuthorize("@pms.hasPermission('swsttvmsupplementcurrency_edit')" )
    public R updateById(@RequestBody SwStTvmSupplementCurrencyDTO swStTvmSupplementCurrencyDTO,String cashBoxType) {
        SwStTvmSupplementCurrency currency = swStTvmSupplementCurrencyService.getById(swStTvmSupplementCurrencyDTO.getSupplementCurrency().getId());
        if(ObjectUtil.isNotEmpty(currency)){
            String approvalStatus = currency.getApprovalStatus();
            if("1".equals(approvalStatus)){
                return R.failed(StmConstans.failedEdit);
            }
        }
        return R.ok(swStTvmSupplementCurrencyService.updateSwStTvmSupplementCurrency(swStTvmSupplementCurrencyDTO,cashBoxType));
    }

    /**
     * 通过id查询TVM补币金额（主表）历史记录
     *
     * @param  id
     * @return R
     */
    @ApiOperation(value = "通过id查询TVM补币金额（主表）历史记录", notes = "通过id查询TVM补币金额（主表）历史记录")
    @GetMapping("getLogById/{id}")
    public R getLogById(@PathVariable("id") Integer id) {
        List<SwStmStationDataEntryLogDvo> LogInfoList = new ArrayList<>();
        List<SwStmStationDataEntryLog> swStmStationDataEntryLogs = swStmStationDataEntryLogService.getBaseMapper()
                .selectList(Wrappers.<SwStmStationDataEntryLog>lambdaQuery()
                        .eq(SwStmStationDataEntryLog::getRelationId, id)
                        .eq(SwStmStationDataEntryLog::getLogTableName, StmTableCommon.SW_ST_TVM_SUPPLEMENT_CURRENCY));
        //返回json串
        if(CollectionUtil.isNotEmpty(swStmStationDataEntryLogs)){
            swStmStationDataEntryLogs.stream().forEach(x -> {
                JSONObject jsonObject = JSONObject.parseObject(x.getLogInfo());
                SwStmStationDataEntryLogDvo swStmStationDataEntryLogDvo = new SwStmStationDataEntryLogDvo();
                BeanUtils.copyProperties(x,swStmStationDataEntryLogDvo);
                swStmStationDataEntryLogDvo.setLogInfo(jsonObject);
                LogInfoList.add(swStmStationDataEntryLogDvo);
            });
        }
        //List<String> LogInfoList = swStmStationDataEntryLogs.stream().map(SwStmStationDataEntryLog::getLogInfo).collect(Collectors.toList());
        return R.ok(LogInfoList);
    }

    /**
     * 通过记录表id查询具体的补币信息详情历史记录
     *
     * @param  id
     * @return R
     */
    @ApiOperation(value = "通过记录表id查询具体的补币信息详情历史记录", notes = "通过记录表id查询具体的补币信息详情历史记录")
    @GetMapping("getLogChildById/{id}")
    public R getLogChildById(@PathVariable("id") Integer id) {
        List<Object> LogInfoList = new ArrayList<>();
            List<SwStmStationDataEntryLog> swStmStationDataEntryLogs = swStmStationDataEntryLogService.getBaseMapper()
                    .selectList(Wrappers.<SwStmStationDataEntryLog>lambdaQuery()
                            .eq(SwStmStationDataEntryLog::getMainId,id)
                            .eq(SwStmStationDataEntryLog::getLogTableName, StmTableCommon.SW_ST_TVM_SUPPLEMENT_CURRENCY_DETAILS));
            //返回json串
            if(CollectionUtil.isNotEmpty(swStmStationDataEntryLogs)){
                //List<String> LogInfoList = swStmStationDataEntryLogs.stream().map(SwStmStationDataEntryLog::getLogInfo).collect(Collectors.toList());
                if(CollectionUtil.isNotEmpty(swStmStationDataEntryLogs)){
                    swStmStationDataEntryLogs.stream().forEach(x -> {
                        JSONObject jsonObject = JSONObject.parseObject(x.getLogInfo());
                        LogInfoList.add(jsonObject);
                    });
                }
                return R.ok(LogInfoList);
            }
        return R.ok();
    }

    /**
     * 通过id删除TVM补币金额管理
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除TVM补币金额管理", notes = "通过id删除TVM补币金额管理")
    //@SysLog("通过id删除TVM补币金额管理" )
    @DeleteMapping("/{id}" )
    @PreAuthorize("@pms.hasPermission('swsttvmsupplementcurrency_del')" )
    public R removeById(@PathVariable Integer id) {
        return R.ok(swStTvmSupplementCurrencyService.deleteCascadeById(id));
    }

    /**
     * 查询tvm日营收详情
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询具体的补币信息详情", notes = "通过id查询")
    @GetMapping("/details/{id}" )
    public R getSwTvmCheckDetails(@PathVariable("id" ) Integer id) {
        return R.ok(swStTvmSupplementCurrencyService.queryDetailsByid(id));
    }

    /**
     * 查询硬币钱箱
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询具体的硬币钱箱补币信息详情", notes = "通过id查询")
    @GetMapping("/coindetails/{id}" )
    public R getSupplementCoinDetails(@PathVariable("id" ) Integer id) {
        return R.ok(swStTvmSupplementCurrencyService.queryCoinDetailsByid(id));
    }

    /**
     * 查询纸币钱箱
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询具体的纸币钱箱补币信息详情", notes = "通过id查询")
    @GetMapping("/paperdetails/{id}" )
    public R getSupplementPaperDetails(@PathVariable("id" ) Integer id) {
        return R.ok(swStTvmSupplementCurrencyService.queryPaperDetailsByid(id));
    }

    /**
     * 批量删除子表
     *
     * @param idList
     * @return
     */
    //@SysLog("通过id批量删除TVM补币金额管理")
    @DeleteMapping("/batchCascadeDel")
    @PreAuthorize("@pms.hasPermission('swsttvmsupplementcurrency_batch_del')")
    @Transactional
    @ApiOperation(value = "通过id批量删除TVM补币金额管理", notes = "通过id批量删除TVM补币金额管理")
    public R batchRemoveById(@RequestBody List<Integer> idList) {
        List<SwStTvmSupplementCurrency> list = swStTvmSupplementCurrencyService.list(new QueryWrapper<SwStTvmSupplementCurrency>().lambda().in(SwStTvmSupplementCurrency::getId, idList));
        List<Integer> deleteIds = list.stream().filter(x -> !x.getApprovalStatus().equals(CommonConstants.SUBMIT)).map(x -> x.getId()).collect(Collectors.toList());
        if(CollectionUtil.isEmpty(deleteIds)){
            return R.failed(StmConstans.failedDelete);
        }
        deleteIds.forEach(swStTvmSupplementCurrencyService::deleteCascadeById);
        return R.ok();
    }

    /**
     * 导出补币金额数据
     * @param page
     * @param supplementCurrency
     * @param response
     */
    @ApiOperation(value = "导出补币金额数据", notes = "导出钱箱未卸载数据")
    @GetMapping("/export")
    public void export(Page page, SwStTvmSupplementCurrency supplementCurrency, HttpServletResponse response) {
        List<SwStTvmSupplementCurrency> records = swStTvmSupplementCurrencyService.page(page, Wrappers.query(supplementCurrency)).getRecords();
        try {
            R<List<SysDictItem>> inputDataStatus = systemUserService.getDictByType(StmConstans.STM_INPUT_DATA_STATUS);
            List<SysDictItem> dictData = inputDataStatus.getData();
            if (CollectionUtil.isNotEmpty(records)) {
                Map<String, String> map = dictData.stream().collect(Collectors.toMap(SysDictItem::getValue, SysDictItem::getLabel));
                for (SwStTvmSupplementCurrency record : records) {
                    record.setApprovalStatus(map.get(record.getApprovalStatus()));
                }
            }
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("补币金额数据", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + System.currentTimeMillis() + ".xlsx");
            EasyExcel.write(response.getOutputStream(), SwStTvmSupplementCurrency.class).
                    sheet("补币金额数据").doWrite(records);
        } catch (IOException e) {
            log.error("补币金额数据导出失败");
        }
    }


}
